﻿#include"stdafx.h"
#include"ServerDB.h"
int ServerDB::Table_Delete(const char*tname, string db, vector<struct_where>where, string &msg) {
	cur_db = db.c_str();
	if (cur_db == "") {
		msg = "Please choose a database !";
		return 0;
	}
	CString  tbPath; tbPath = L"data\\" + cur_db + L"\\" + cur_db + L".tb";

	if (!IsTable(tbPath, tname)) {
		msg = "Incorrect table name !";
		return false;
	}

	CString DBPath; 
	CString Ctname;
	Ctname = tname; 
	bool index = false;
	Table_Tdf tdf;
	vector<Table_Tdf>vec_tdf;
	DBPath = L"data\\" + cur_db + L"\\" + Ctname + L".tdf";

	file.Open(DBPath, CFile::modeRead | CFile::typeBinary, NULL);
	while (file.Read(&tdf, sizeof(tdf))) {
		vec_tdf.push_back(tdf);
	}
	file.Close();

	//判断where字段是否合法
	index = true;
	for (unsigned int i = 0; i < where.size(); i++) {
		for (unsigned int j = 0; j < vec_tdf.size(); j++) {
			if (strcmp(vec_tdf[j].name, where[i].key.c_str()) == 0) {
				where[i].pos = vec_tdf[j].order;
				where[i].size = vec_tdf[j].param;
				where[i].index = vec_tdf[j].index;
				where[i].type = vec_tdf[j].type;

				if (where[i].type == "5" && !IsDateValid(where[i].value.c_str())) {
					msg = "Invalid date in where";
					return 0;
				}
				index = false;
			}
		}
		if (index) {
			msg = "Invalid column in where";
			return 0;
		}
		index = true;
	}

	Table_Tdf Ttdf = vec_tdf.back();
	int lenth = Ttdf.order + Ttdf.param;

	DBPath = L"data\\" + cur_db + L"\\" + Ctname + L".trd";
	CString temp_path = L"data\\" + cur_db + L"\\" + Ctname + L".trd.temp";
	CFile temp_file;
	temp_file.Open(temp_path, CFile::modeCreate);
	temp_file.Close();
	file.Open(DBPath, CFile::modeRead | CFile::typeBinary, NULL);
	temp_file.Open(temp_path, CFile::modeWrite | CFile::typeBinary, NULL);

		int offset = 0;
		while (file.GetLength()>offset) {
			Traversal(file, temp_file, offset,lenth, where);
			offset += lenth;
		}
	
	file.Close();
	temp_file.Close();
	file.Remove(DBPath);
	file.Rename(temp_path, DBPath);


	//生成新的索引
	string tpath = "data\\" + db + "\\" + tname;	
	for (unsigned int i = 0; i < vec_tdf.size(); i++) {
		if (vec_tdf[i].index) {
			int size = vec_tdf[i].param;
			string auth  = db + "_" + tname + "_" + vec_tdf[i].name;
			if (vec_tdf[i].type == "4")
				size = 256;
			indexM.ReProduceIndex(tpath, vec_tdf[i].name,auth, vec_tdf[i].order, lenth, size);
		}
	}
	msg = "successful!";
	return 0;
}